<template>
  <div v-loading="loading" class="set" style="height: 100%" element-loading-text="加载中...">
    <el-form ref="formRef" label-width="auto" :rules="rules" :model="userForm">
      <el-form-item label="默认条码" class="form-item" prop="code">
        <div>
          <el-input
            v-model.trim="userForm.code"
            class="item-width"
            maxlength="10"
            clearable
            placeholder="默认条码"
          />
          <div class="tips">默认客户唯一识别码编号头，条码开头不超过3位</div>
        </div>
      </el-form-item>
      <el-form-item label="知识库查看权限" class="form-item">
        <div>
          <el-radio-group v-model="userForm.selectKnowledgeAuthor">
            <el-radio :value="false">
              <span class="bg_text">查看所有</span>
            </el-radio>
            <el-radio :value="true">
              <span class="bg_text">按客户分类查看</span>
            </el-radio>
          </el-radio-group>
          <div class="tips">是否允许查看知识库</div>
        </div>
      </el-form-item>
      <el-form-item label="默认级别" class="form-item">
        <div>
          <el-select
            v-model="userForm.levelId"
            class="item-width"
            placeholder="请选择级别"
            filterable
            reserve-keyword
            remote-show-suffix
            :loading="userForm.loading"
            :filter-method="searchLevelSelect"
          >
            <el-option
              v-for="item in userForm.options"
              :key="item.id"
              :label="item.name"
              :value="item.id"
            />
          </el-select>
          <div class="tips">设置用户默认级别</div>
        </div>
      </el-form-item>
      <el-form-item label="客户端登录设置" class="form-item">
        <div>
          <el-radio-group v-model="userForm.mobileHasLogin">
            <el-radio :value="true">
              <span class="bg_text">开启</span>
            </el-radio>
            <el-radio :value="false">
              <span class="bg_text">关闭</span>
            </el-radio>
          </el-radio-group>
          <div class="tips">客户移动端开启必须登录</div>
        </div>
      </el-form-item>
    </el-form>
    <div class="btns">
      <HPlainButton @click="saveSet(formRef)">保存</HPlainButton>
    </div>
  </div>
</template>

<script setup lang="ts">
  import { ref, onMounted, reactive, markRaw } from 'vue'
  import type { FormInstance } from 'element-plus'
  import { Warning } from '@element-plus/icons-vue'
  import { ElMessage, ElMessageBox } from 'element-plus'
  import { getUserSet, saveUserSet, levelPageSelect } from '@/api/users'
  import _ from 'lodash'
  import HPlainButton from '@/components/common/button/HPlainButton.vue'
import { HMessage, HMessageBox } from '@/components/common/message'

  const loading = ref(false)

  const props = defineProps({
    active_name: String,
  })

  // 用户设置数据
  const userForm = reactive({
    code: '',
    id: '',
    selectKnowledgeAuthor: false,
    levelId: '',
    levelVal: '',
    loading: false,
    options: [],
    mobileHasLogin: true, //客户移动端是否开启必须登录：false-关闭，true-开启
  })

  const formRef = ref<FormInstance>()

  // 验证规则
  const rules = reactive({
    code: [
      { required: true, message: '请输入默认条码', trigger: 'blur' },
      {
        pattern: /^[A-Za-z1-9]{1,10}$/,
        message: '格式错误',
        trigger: 'blur',
      },
    ],
  })

  // 获取设置数据
  const getSet = async () => {
    loading.value = true
    await getUserSet().then((res) => {
      userForm.code = res.data.data.row.code
      userForm.id = res.data.data.row.id
      userForm.selectKnowledgeAuthor = res.data.data.row.selectKnowledgeAuthor
      userForm.levelId = res.data.data.row.levelId == 0 ? null : res.data.data.row.levelId
      userForm.mobileHasLogin = res.data.data.row.mobileHasLogin
    })
    loading.value = false
  }

  // 获取分页数据
  const getPageData = (name) => {
    return {
      limit: 0,
      name: name,
      page: 0,
    }
  }

  // 获取级别下拉
  const getOptions = async (name: string) => {
    userForm.loading = true
    const res = await levelPageSelect(getPageData(name))
    userForm.options = res.data.data.rows
    userForm.loading = false
  }

  /**
   * 搜索级别下拉数据
   * @param {string} query 搜索关键字
   */
  const searchLevelSelect = _.throttle((query: string) => {
    if (userForm.levelVal !== query) {
      userForm.levelVal = query
      getOptions(userForm.levelVal)
    }
  }, 500)

  // 封装保存的方法
  const saveMethod = async (data, method) => {
    ElMessageBox({
      type: 'warning',
      title: '提示',
      message: '确认保存设置?',
      showCancelButton: true,
      closeOnClickModal: false,
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      beforeClose: (action, instance, done) => {
        if (action === 'confirm') {
          instance.confirmButtonLoading = true
          instance.confirmButtonText = '加载中...'
          setTimeout(() => {
            done()
            setTimeout(() => {
              instance.confirmButtonLoading = false
            }, 0)
          }, 1000)
        } else {
          done()
        }
      },
    }).then(() => {
      method(data).then((res) => {
        if (res.data.success == true) {
          HMessage.success('保存成功')
          getSet()
        } else {
          HMessageBox.error(res.data.message)
          return
        }
      })
    })
  }

  // 保存设置
  const saveSet = (formEl: FormInstance | undefined) => {
    formEl.validate((valid) => {
      if (valid) {
        const data = {
          code: userForm.code,
          id: userForm.id,
          selectKnowledgeAuthor: userForm.selectKnowledgeAuthor,
          levelId: userForm.levelId,
          mobileHasLogin: userForm.mobileHasLogin,
        }
        saveMethod(data, saveUserSet)
      }
    })
  }

  onMounted(() => {
    if (props.active_name == 'set') {
      getSet()
      getOptions('')
    }
  })

  defineExpose({ getSet })
</script>

<style scoped lang="scss">
  @import '../../index.scss';
</style>
